<template>
  <div class="battery-detail-page">
    <van-nav-bar title="电池详情" left-arrow @click-left="router.back()" fixed />

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" success-text="刷新成功" class="full-height">
      <div class="content">
        <!-- 车辆图片
        <div class="vehicle-image-container">
          <img :src="vehicleImage" alt="车辆图片" class="vehicle-image" />
          <div class="vehicle-info-overlay">
            <div class="vehicle-name">{{ vehicleInfo.vehicleName || '我的爱车' }}</div>
            <div class="vehicle-model">{{ vehicleInfo.vehicleModel || '-' }}</div>
          </div>
        </div> -->

        <!-- 电池状态卡片 -->
        <div class="battery-card">
          <div class="battery-status">
            <div class="battery-icon"
              :class="{ 'charging': batteryInfo.whetherChargeState || batteryDetailInfo.chargeState === '1' }">
              <div class="battery-body">
                <div class="battery-level" :style="{ height: `${batteryInfo.bmssoc || '0'}%` }"
                  :class="getBatteryLevelClass(batteryInfo.bmssoc)">
                  <div class="battery-wave"
                    v-if="batteryInfo.whetherChargeState || batteryDetailInfo.chargeState === '1'"></div>
                </div>
              </div>
              <div class="battery-tip"></div>
            </div>

            <div class="battery-info">
              <div class="battery-percentage">{{ batteryInfo.bmssoc || '0' }}%</div>
              <div class="battery-status-text"
                :class="{ 'charging-text': batteryInfo.whetherChargeState || batteryDetailInfo.chargeState === '1' }">
                {{ batteryInfo.chargeStateStr || (batteryDetailInfo.chargeState === '1' ? '充电中' : '未充电') }}
              </div>
              <!-- 预计充满时间 -->
              <div class="full-charge-info"
                v-if="batteryInfo.whetherChargeState || batteryDetailInfo.chargeState === '1'">
                <van-icon name="underway-o" />
                <span>预计{{ batteryDetailInfo.fullChargeTime || '0.0' }}小时{{ batteryDetailInfo.fullChargeTimeUnitMinute
                  || '0'
                  }}分钟充满</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 里程可视化 -->
        <div class="detail-card mileage-card">
          <div class="card-header">
            <div class="card-title">剩余里程</div>
            <div class="mileage-value">{{ batteryInfo.hmiRidableMile || '0' }} <span>km</span></div>
          </div>
          <div class="mileage-gauge">
            <div class="gauge-track"></div>
            <div class="gauge-fill" :style="{width: `${calculateMileagePercentage()}%`}"></div>
            <div class="gauge-marker" :style="{left: `${calculateMileagePercentage()}%`}"></div>
          </div>
          <div class="gauge-labels">
            <span>0</span>
            <span>{{ maxRidingDistance }}km</span>
          </div>
        </div>

        <!-- 电池详情数据 -->
        <div class="detail-card">
          <div class="card-title">电池数据</div>
          <div class="data-grid">
            <div class="data-item">
              <div class="data-label">剩余电量</div>
              <div class="data-value">{{ batteryInfo.bmssoc || '0' }}%</div>
            </div>
            <div class="data-item">
              <div class="data-label">剩余里程</div>
              <div class="data-value">{{ batteryInfo.hmiRidableMile || '0' }}km</div>
            </div>
            <div class="data-item" v-if="batteryInfo.soh">
              <div class="data-label">电池健康度</div>
              <div class="data-value">{{ batteryInfo.soh }}%</div>
            </div>
            <div class="data-item" v-if="batteryInfo.batteryTemp">
              <div class="data-label">电池温度</div>
              <div class="data-value">{{ batteryInfo.batteryTemp }}°C</div>
            </div>
            <div class="data-item">
              <div class="data-label">当前电压</div>
              <div class="data-value">{{ batteryInfo.bmsVoltage || batteryDetailInfo.bmsVoltage || '0' }}V</div>
            </div>
            <div class="data-item"
              v-if="(batteryInfo.whetherChargeState || batteryDetailInfo.chargeState === '1') && batteryDetailInfo.bmsCurrent">
              <div class="data-label">当前电流</div>
              <div class="data-value">{{ batteryDetailInfo.bmsCurrent || '0' }}A</div>
            </div>
            <div class="data-item"
              v-if="(batteryInfo.whetherChargeState || batteryDetailInfo.chargeState === '1') && batteryDetailInfo.power">
              <div class="data-label">充电功率</div>
              <div class="data-value">{{ batteryDetailInfo.power || '0.0' }}kW</div>
            </div>
            <div class="data-item">
              <div class="data-label">电池评分</div>
              <div class="data-value" :class="{ 'score-good': batteryInfo.score === '优' }">
                {{ batteryInfo.score || '良好' }}
              </div>
            </div>
          </div>
        </div>

        <!-- 用电统计 -->
        <div class="detail-card">
          <div class="card-title">用电统计</div>
          <div class="data-grid">
            <div class="data-item">
              <div class="data-label">今日用电</div>
              <div class="data-value">{{ batteryInfo.powerUseToday || '0' }}kWh</div>
            </div>
            <div class="data-item">
              <div class="data-label">本月用电</div>
              <div class="data-value">{{ batteryInfo.powerUseMonth || '0' }}kWh</div>
            </div>
            <div class="data-item">
              <div class="data-label">本月充电</div>
              <div class="data-value">{{ batteryInfo.powerChargeMonth || '0' }}kWh</div>
            </div>
            <div class="data-item">
              <div class="data-label">充电次数</div>
              <div class="data-value">{{ batteryInfo.chargeCount || '0' }}次</div>
            </div>
          </div>
        </div>

        <!-- 充电建议卡片 -->
        <div class="detail-card tips-card">
          <div class="card-title">充电建议</div>
          <div class="tips-content">
            <van-icon name="bulb-o" class="tips-icon" />
            <div class="tips-text">
              <p v-if="getBatteryLevel() === 'low'">
                建议尽快充电，当前电量较低。避免电池过度放电，可延长电池寿命。
              </p>
              <p v-else-if="getBatteryLevel() === 'medium'">
                电池处于正常工作状态。如有长途行程，建议提前充电。
              </p>
              <p v-else>
                电量充足，可以轻松应对日常出行。建议保持良好的充电习惯，避免电池频繁充放电。
              </p>
            </div>
          </div>
        </div>

        <!-- 最大续航 -->
        <div class="detail-card" v-if="batteryInfo.maxMileage">
          <div class="card-title">最大续航</div>
          <div class="max-mileage">
            <van-icon name="flag-o" />
            <span>{{ batteryInfo.maxMileage }}km</span>
          </div>
        </div>

        <!-- 数据刷新时间 -->
        <div class="refresh-time">
          数据更新时间: {{ batteryInfo.refreshTime || formatCurrentTime() }}
        </div>
      </div>
    </van-pull-refresh>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showLoadingToast, closeToast, showSuccessToast, showFailToast } from 'vant';
import { getBatteryInfo, getBatteryDetailInfo } from '@/api/vehicle';
import { useVehicleStore } from '@/stores/vehicle';
import { useApiPolling } from '@/utils/api-polling.js';

const router = useRouter();
const route = useRoute();
const vehicleStore = useVehicleStore();
const refreshing = ref(false);

// 车辆信息
const vehicleInfo = computed(() => vehicleStore.getCurrentVehicle() || {});

// 车辆图片
const vehicleImage = ref(getRandomVehicleImage());

// 最大骑行距离（用于仪表盘）
const maxRidingDistance = ref(120);

// 电池信息
const batteryInfo = ref({
  chargeState: "",
  bmssoc: "0",
  hmiRidableMile: "0",
  powerUseToday: "0",
  powerChargeMonth: "0",
  powerUseMonth: "0",
  chargeCount: "0",
  score: "良好",
  bmsVoltage: "0",
  batteryTemp: null,
  soh: null,
  batteryLevel: "0",
  whetherChargeState: false,
  chargeStateStr: "未充电",
  maxMileage: null,
  refreshTime: ""
});

// 电池详情信息
const batteryDetailInfo = ref({
  chargeState: "0",
  bmsCurrent: "0",
  bmsVoltage: "0",
  power: "0.0",
  fullChargeTime: "0.0",
  fullChargeTimeUnitMinute: "0"
});

// 获取随机车辆图片
function getRandomVehicleImage() {
  const images = [
    '/src/assets/kzq/CF72290.png',
    '/src/assets/kzq/NB72290.png',
    '/src/assets/kzq/CF72350.jpg'
  ];
  return images[Math.floor(Math.random() * images.length)];
}

// 获取电池电量等级的样式类
const getBatteryLevelClass = (level) => {
  const numLevel = Number(level);
  if (numLevel <= 20) return 'level-low';
  if (numLevel <= 50) return 'level-medium';
  return 'level-high';
};

// 获取电池电量等级
const getBatteryLevel = () => {
  const level = Number(batteryInfo.value.bmssoc || 0);
  if (level <= 20) return 'low';
  if (level <= 50) return 'medium';
  return 'high';
};

// 计算里程百分比
const calculateMileagePercentage = () => {
  const currentMileage = Number(batteryInfo.value.hmiRidableMile || 0);
  return Math.min(Math.max((currentMileage / maxRidingDistance.value) * 100, 0), 100);
};

// 格式化当前时间
const formatCurrentTime = () => {
  const now = new Date();
  return now.toLocaleString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 获取电池信息
const fetchBatteryInfo = async () => {
  const vinNo = route.query.vinNo;
  if (!vinNo) {
    showFailToast('缺少车辆信息');
    return;
  }

  try {
    showLoadingToast({
      message: '获取数据中...',
      forbidClick: true,
      duration: 0,
    });

    // 获取deviceId（如果没有提供，则使用vinNo）
    const deviceId = route.query.deviceId || '358122500065887'; // 使用URL参数或默认值

    // 并行获取两个接口数据
    const [batteryResponse, batteryDetailResponse] = await Promise.all([
      getBatteryInfo(vinNo),
      getBatteryDetailInfo(deviceId)
    ]);

    if (batteryResponse.code === '10000' && batteryResponse.data) {
      batteryInfo.value = batteryResponse.data;
      
      // 更新最大骑行距离
      if (batteryResponse.data.maxMileage) {
        maxRidingDistance.value = Number(batteryResponse.data.maxMileage);
      }
    }

    if (batteryDetailResponse.code === '10000' && batteryDetailResponse.data) {
      batteryDetailInfo.value = batteryDetailResponse.data;
    }

  } catch (error) {
    console.error('获取电池信息失败:', error);
    showFailToast(error.message || '获取电池信息失败');

    // 开发环境使用模拟数据
    if (import.meta.env.DEV) {
      useMockData();
    }
  } finally {
    closeToast();
  }
};

// 下拉刷新
const onRefresh = async () => {
  try {
    await fetchBatteryInfo();
  } finally {
    refreshing.value = false;
  }
};

// 开发环境使用模拟数据
const useMockData = () => {
  batteryInfo.value = {
    chargeState: "1",
    bmssoc: "75",
    hmiRidableMile: "87",
    powerUseToday: "1.2",
    powerChargeMonth: "15.5",
    powerUseMonth: "18.7",
    chargeCount: "12",
    score: "优",
    bmsVoltage: "75",
    batteryTemp: "28",
    soh: "98",
    batteryLevel: "75",
    whetherChargeState: true,
    chargeStateStr: "充电中",
    maxMileage: "120",
    refreshTime: formatCurrentTime()
  };

  batteryDetailInfo.value = {
    chargeState: "1",
    bmsCurrent: "3.9",
    bmsVoltage: "76.2",
    power: "0.8",
    fullChargeTime: "0.5",
    fullChargeTimeUnitMinute: "30"
  };
};

const {
  start,
  stop,
  executeNow,
  updateInterval,
  setup
} = useApiPolling(fetchBatteryInfo, 60000, false);

// 组件销毁时停止轮询
onUnmounted(() => {
  stop();
});

onMounted(() => {
  // 尝试从车辆信息中获取图片
  if (vehicleInfo.value && vehicleInfo.value.vehicleImage) {
    vehicleImage.value = vehicleInfo.value.vehicleImage;
  }
  
  start();
});

</script>

<style lang="scss" scoped>
.battery-detail-page {
  background-color: #f8f8fa;
  height: 100%;
  display: flex;
  flex-direction: column;


  .full-height {
    flex: 1;
    overflow-y: auto;
    padding-top: 46px;

    // 隐藏滚动条
    &::-webkit-scrollbar {
      display: none;
    }

  }

  .content {
    padding: 12px;
  }

  // 车辆图片
  .vehicle-image-container {
    position: relative;
    height: 180px;
    border-radius: 16px;
    overflow: hidden;
    margin-bottom: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    
    .vehicle-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    .vehicle-info-overlay {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      padding: 15px;
      background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
      color: white;
      
      .vehicle-name {
        font-size: 18px;
        font-weight: 600;
        margin-bottom: 4px;
      }
      
      .vehicle-model {
        font-size: 14px;
        opacity: 0.9;
      }
    }
  }

  // 电池状态卡片
  .battery-card {
    background: linear-gradient(135deg, #4285F4, #2563eb);
    border-radius: 16px;
    padding: 20px;
    color: white;
    box-shadow: 0 4px 12px rgba(37, 99, 235, 0.2);
    margin-bottom: 12px;

    .battery-status {
      display: flex;
      align-items: center;
    }

    .battery-icon {
      position: relative;
      width: 50px;
      height: 80px;
      margin-right: 20px;
      flex-shrink: 0;

      .battery-body {
        width: 100%;
        height: calc(100% - 6px);
        background: rgba(255, 255, 255, 0.2);
        border-radius: 6px;
        position: relative;
        overflow: hidden;
      }

      .battery-tip {
        position: absolute;
        top: -3px;
        left: 50%;
        transform: translateX(-50%);
        width: 18px;
        height: 3px;
        background: rgba(255, 255, 255, 0.2);
        border-radius: 3px 3px 0 0;
      }

      .battery-level {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        background: white;
        border-radius: 0 0 6px 6px;
        transition: height 1s cubic-bezier(0.23, 1, 0.32, 1);
        min-height: 4%;
        /* 确保即使电量为0也有一点显示 */

        &.level-high {
          background: #34d399;
        }

        &.level-medium {
          background: #fbbf24;
        }

        &.level-low {
          background: #ef4444;
        }
      }

      &.charging {
        animation: battery-pulse 2s infinite ease-in-out;

        &::after {
          content: '⚡';
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          font-size: 18px;
          opacity: 0;
          animation: flash-in-out 2s infinite;
        }

        .battery-body {
          box-shadow: 0 0 8px rgba(52, 211, 153, 0.8);
        }

        .battery-level {
          position: relative;
          overflow: hidden;

          .battery-wave {
            position: absolute;
            top: -10px;
            left: 0;
            width: 200%;
            height: 14px;
            background: repeating-linear-gradient(to right,
                rgba(255, 255, 255, 0.5),
                rgba(255, 255, 255, 0.5) 3px,
                transparent 3px,
                transparent 6px);
            animation: wave 1.5s linear infinite, pulse-opacity 2s ease-in-out infinite;
          }
        }
      }
    }

    .battery-info {
      flex: 1;

      .battery-percentage {
        font-size: 28px;
        font-weight: 600;
        margin-bottom: 2px;
      }

      .battery-status-text {
        font-size: 15px;
        opacity: 0.9;
        margin-bottom: 8px;

        &.charging-text {
          color: #4ade80;
          display: flex;
          align-items: center;

          &::before {
            content: '';
            display: inline-block;
            width: 8px;
            height: 8px;
            background-color: #4ade80;
            border-radius: 50%;
            margin-right: 6px;
            animation: pulse 1.5s infinite;
          }
        }
      }
    }

    .full-charge-info {
      display: flex;
      align-items: center;
      font-size: 13px;
      opacity: 0.9;

      .van-icon {
        margin-right: 6px;
        animation: rotate-icon 1.5s linear infinite;
      }
    }
  }

  // 里程仪表盘
  .mileage-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      
      .mileage-value {
        font-size: 20px;
        font-weight: 600;
        color: #2563eb;
        
        span {
          font-size: 14px;
          font-weight: normal;
          color: #666;
        }
      }
    }
    
    .mileage-gauge {
      position: relative;
      height: 8px;
      margin: 10px 0;
      
      .gauge-track {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 100%;
        background-color: #e5e7eb;
        border-radius: 4px;
      }
      
      .gauge-fill {
        position: absolute;
        top: 0;
        left: 0;
        height: 100%;
        background: linear-gradient(to right, #3b82f6, #2563eb);
        border-radius: 4px;
        transition: width 0.5s ease;
      }
      
      .gauge-marker {
        position: absolute;
        top: -4px;
        width: 16px;
        height: 16px;
        background-color: #2563eb;
        border: 3px solid #fff;
        border-radius: 50%;
        transform: translateX(-50%);
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        transition: left 0.5s ease;
      }
    }
    
    .gauge-labels {
      display: flex;
      justify-content: space-between;
      margin-top: 8px;
      font-size: 12px;
      color: #666;
    }
  }

  // 详情卡片样式
  .detail-card {
    background-color: white;
    border-radius: 12px;
    padding: 14px;
    margin-bottom: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .card-title {
      font-size: 15px;
      font-weight: 500;
      margin-bottom: 14px;
      color: #333;
      display: flex;
      align-items: center;

      &::before {
        content: '';
        width: 3px;
        height: 14px;
        background-color: #2563eb;
        border-radius: 1.5px;
        margin-right: 8px;
        display: inline-block;
      }
    }

    .data-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 14px;

      .data-item {
        .data-label {
          font-size: 12px;
          color: #666;
          margin-bottom: 3px;
        }

        .data-value {
          font-size: 15px;
          color: #333;
          font-weight: 500;

          &.score-good {
            color: #10b981;
          }
        }
      }
    }

    .max-mileage {
      display: flex;
      align-items: center;
      font-size: 16px;
      color: #333;
      font-weight: 500;

      .van-icon {
        margin-right: 8px;
        color: #2563eb;
      }
    }
  }
  
  // 充电建议卡片
  .tips-card {
    .tips-content {
      display: flex;
      align-items: flex-start;
      
      .tips-icon {
        font-size: 18px;
        color: #f59e0b;
        margin-right: 10px;
        margin-top: 2px;
      }
      
      .tips-text {
        flex: 1;
        font-size: 14px;
        line-height: 1.5;
        color: #4b5563;
        
        p {
          margin: 0;
        }
      }
    }
  }

  // 刷新时间
  .refresh-time {
    text-align: center;
    font-size: 12px;
    color: #999;
    margin-top: 6px;
    margin-bottom: 16px;
  }
}

// 动画
@keyframes wave {
  from {
    transform: translateX(0);
  }

  to {
    transform: translateX(-50%);
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }

  50% {
    transform: scale(1.2);
    opacity: 0.7;
  }

  100% {
    transform: scale(1);
    opacity: 1;
  }
}

@keyframes pulse-opacity {
  0% {
    opacity: 0.5;
  }

  50% {
    opacity: 1;
  }

  100% {
    opacity: 0.5;
  }
}

@keyframes battery-pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

@keyframes flash-in-out {
  0% {
    opacity: 0;
    transform: translate(-50%, -50%) scale(0.8);
  }
  10% {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1);
  }
  50% {
    opacity: 0;
    transform: translate(-50%, -50%) scale(1.2);
  }
  100% {
    opacity: 0;
    transform: translate(-50%, -50%) scale(0.8);
  }
}

@keyframes rotate-icon {
  0% {
    transform: rotate(0deg);
  }

  50% {
    transform: rotate(180deg);
  }

  100% {
    transform: rotate(360deg);
  }
}
</style>